﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ZLCMS.Business;
using ZLCMS.Business.DwzFrame;
using ZLCMS.Data.Model;
using NHibernate;
using Senparc.Weixin.MP.Entities;
using NHibernate.Criterion;
using System.Collections.Generic;
using ZLCMS.Business.Util;
using Senparc.Weixin.MP.Helpers;
using DotNet.Common.NHibernateUtil;
using Newtonsoft.Json;
using ZLCMS.Business.WeixinService.Data;

namespace ZLCMS.Web.SystemManage.Weixin
{
    public partial class Edit2048 : System.Web.UI.Page
    {
        protected FrameHelper _frameHelper;

        protected WxGamesConfig _gameDb;
        protected WxMaterial _materialDb;

        private string _uid;

        protected string _userAccount;

        protected void Page_Load(object sender, EventArgs e)
        {
            _userAccount = UserKit.GetUserAccountFailLogin();

            _frameHelper = new FrameHelper(this);

            //初始化全局变量值
            InitializeGlobalValue();
            //初始化控件值
            InitializeContent();

            if (IsPostBack)
            {
                Save();
            }
        }

        #region 保存操作 新建/更新 + private void Save()
        /// <summary>
        /// 保存操作 新建/更新
        /// </summary>
        private void Save()
        {
           
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                ITransaction tran = session.BeginTransaction();
                try
                {
                    if (string.IsNullOrEmpty(_uid))//新建
                    {
                        _materialDb = new WxMaterial();

                        _materialDb.Title = tb_name.Text;
                        _materialDb.MsgType = "Block";
                        _materialDb.CreateDate = DateTime.Now;
                        _materialDb.UpdateDate = DateTime.Now;
                        _materialDb.Status = "1";
                        _materialDb.OwnerAccount = _userAccount;

                        session.Save(_materialDb);

                        _gameDb = new WxGamesConfig();

                        _gameDb.Title = tb_name.Text;
                        _gameDb.Description = tb_desc.Text;
                        _gameDb.Content = txtContent.Value;

                        _gameDb.BeginDate = DateTime.Parse(tb_sdate.Text);
                        _gameDb.EndDate = DateTime.Parse(tb_edate.Text);
                        _gameDb.CreateDate = DateTime.Now;

                        _gameDb.ExConfig = JGridControl2.Value;
                        _gameDb.GameBackgroupUrl = fc_background.Value;

                        _gameDb.RuleDay = int.Parse(tb_day.Text);
                        _gameDb.RuleTimes = int.Parse(tb_times.Text);

                        _gameDb.NeedConfig =  0;
                        _gameDb.GameOverTips = tb_tips.Text;
                        _gameDb.WinNotice = tb_win.Text;
                        _gameDb.LostNotice = tb_lost.Text;
                        _gameDb.EndNotice = tb_end.Text;

                        _gameDb.GameOpenUrl = fc_open.Value;
                        _gameDb.GameEndUrl = fc_end.Value;

                        _gameDb.OwnerAccount = _userAccount;
                        _gameDb.GameType = "Block";
                        _gameDb.Status = "SETTING";
                        _gameDb.MaterialId = _materialDb.Id;

                        session.Save(_gameDb);
                    }
                    else//修改
                    {
                        _materialDb.Title = tb_name.Text;

                        _gameDb.Title = tb_name.Text;
                        _gameDb.Description = tb_desc.Text;
                        _gameDb.Content = txtContent.Value;
                        _gameDb.GameOverTips = tb_tips.Text;
                        _gameDb.BeginDate = DateTime.Parse(tb_sdate.Text);
                        _gameDb.EndDate = DateTime.Parse(tb_edate.Text);

                        //活动开始后，不能修改奖品数量
                        if (_gameDb.Status == "SETTING")
                        {
                            _gameDb.AwardConfig = JGridControl2.Value;
                        }

                        _gameDb.GameBackgroupUrl = fc_background.Value;
                        _gameDb.RuleDay = int.Parse(tb_day.Text);
                        _gameDb.RuleTimes = int.Parse(tb_times.Text);
                        
                        _gameDb.NeedConfig = 0;

                        _gameDb.WinNotice = tb_win.Text;
                        _gameDb.LostNotice = tb_lost.Text;
                        _gameDb.EndNotice = tb_end.Text;

                        _gameDb.GameOpenUrl = fc_open.Value;
                        _gameDb.GameEndUrl = fc_end.Value;

                        session.Update(_materialDb);
                        session.Update(_gameDb);
                    }

                    session.Flush();
                    tran.Commit();
                    //session.Flush();
                }
                catch (System.Exception ex)
                {
                    tran.Rollback();
                    _frameHelper.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                    return;
                }
            }

            _frameHelper.Alert(new ReturnCode()
            {
                statusCode = 200,
                message = "操作成功!",
                navTabId = _frameHelper.NavTabId
            });
        } 
        #endregion

        protected void CreateAward(ISession session, WxGamesConfig gameDb)
        {

        }

        #region 初始化全局变量 + protected void InitializeGlobalValue()
        /// <summary>
        /// 初始化全局变量
        /// </summary>
        protected void InitializeGlobalValue()
        {
            if (!IsPostBack)
            {
                ViewState["uid"] = Request["uid"];
            }
            _uid = (string)ViewState["uid"];

            if (!string.IsNullOrEmpty(_uid))
            {
                using (ISession session = SessionFactoryHelper.CreateSession())
                {
                    try
                    {
                        _gameDb = session.CreateCriteria<WxGamesConfig>().Add(Expression.Eq("Id", int.Parse(_uid))).Add(Expression.Eq("OwnerAccount", _userAccount)).UniqueResult<WxGamesConfig>();

                        if (_gameDb == null)
                        {
                            throw new Exception("找不到对应的游戏配置记录.");
                        }
                        else
                        {
                            _materialDb = session.CreateCriteria<WxMaterial>().Add(Expression.Eq("Id", _gameDb.MaterialId)).Add(Expression.Eq("OwnerAccount", _userAccount)).UniqueResult<WxMaterial>();
                            if (_materialDb == null)
                            {
                                throw new Exception("找不到对应的素材记录");
                            }
                        }
                    }
                    catch (System.Exception ex)
                    {
                        _frameHelper.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                        return;
                    }
                }
            }
        } 
        #endregion

        #region 填充页面内容 + protected void InitializeContent()
        /// <summary>
        /// 填充页面内容
        /// </summary>
        protected void InitializeContent()
        {
            //页面控件值
            if (!IsPostBack)
            {
                JGridControl2.Columns.Add(new ListItem() { Text = "项目(不能重复)", Value = "Name" });
                ListItem code = new ListItem() { Text = "编号", Value = "Code" };
                code.Attributes.CssStyle["display"] = "none";
                JGridControl2.Columns.Add(code);

                if (!string.IsNullOrEmpty(_uid))
                {
                    tb_name.Text = _gameDb.Title;
                    tb_desc.Text = _gameDb.Description;
                    txtContent.Value = _gameDb.Content;

                    tb_sdate.Text = _gameDb.BeginDate.ToString("yyyy-MM-dd HH:mm:ss");
                    tb_edate.Text = _gameDb.EndDate.ToString("yyyy-MM-dd HH:mm:ss");

                    JGridControl2.Value = _gameDb.ExConfig;

                    if (_gameDb.Status != "SETTING")
                    {
                        JGridControl2.Readonly = true;
                    }

                    tb_day.Text = _gameDb.RuleDay.ToString();
                    tb_times.Text = _gameDb.RuleTimes.ToString();
                    tb_tips.Text=_gameDb.GameOverTips;
                    tb_win.Text = _gameDb.WinNotice;
                    tb_lost.Text = _gameDb.LostNotice;
                    tb_end.Text = _gameDb.EndNotice;

                    fc_open.Value = _gameDb.GameOpenUrl;
                    fc_end.Value = _gameDb.GameEndUrl;
                    fc_background.Value = _gameDb.GameBackgroupUrl;
                }
                else
                {
                    tb_name.Text = "2048";
                    tb_desc.Text = "亲，请点击进入2084活动页面，祝您好运哦!";
                    txtContent.Value = "亲，请点击进入2048活动页面，祝您好运哦!";

                    tb_sdate.Text = DateTime.Now.Date.ToString("yyyy-MM-dd HH:mm:ss");
                    tb_edate.Text = DateTime.Now.Date.AddDays(7).ToString("yyyy-MM-dd HH:mm:ss");
                    IList<Block2048Item> list = new List<Block2048Item>() {
                        new Block2048Item(){Name= "士兵", Code = "001"},
                        new Block2048Item(){Name= "班长", Code = "002"},
                        new Block2048Item(){Name= "排长", Code = "003"},
                        new Block2048Item(){Name= "连长", Code = "004"},
                        new Block2048Item(){Name= "营长", Code = "005"},
                        new Block2048Item(){Name= "团长", Code = "006"},
                        new Block2048Item(){Name= "旅长", Code = "007"},
                        new Block2048Item(){Name= "师长", Code = "008"},
                        new Block2048Item(){Name= "军长", Code = "009"},
                        new Block2048Item(){Name= "司令", Code = "0010"},
                        new Block2048Item(){Name= "军旗", Code = "0011"},

                    };
                    JGridControl2.Value = JsonConvert.SerializeObject(list);

                    tb_day.Text = "1";
                    tb_times.Text = "1";

                    tb_win.Text = "恭喜您,过关啦！您实在是太厉害了！";
                    tb_lost.Text = "再接再厉哟！";
                    tb_end.Text = "亲，活动已经结束，请继续关注我们的后续活动哦。";

                    fc_open.Value = "[{\"FileId\":\"0\",\"FilePath\":\"/Interface/weixin/images/activity-scratch-card-start.jpg\",\"FileName\":\"刮刮卡.jpg\"}]";
                    fc_end.Value = "[{\"FileId\":\"0\",\"FilePath\":\"/Interface/weixin/images/activity-scratch-card-end.jpg\",\"FileName\":\"刮刮卡.jpg\"}]"; 
                }
            }
        } 
        #endregion
    }
}
